package cuckoo.log;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import cuckoo.log.impl.log4j.Log4jLoggerAdapter;
import cuckoo.log.impl.std.StdLoggerAdapter;

public class LoggerFactory {

	private LoggerFactory() {
	}

	private static volatile LoggerAdapter LOGGER_ADAPTER;
	private static final ConcurrentMap<String, Logger> LOGGERS = new ConcurrentHashMap<String, Logger>();

	static {
		try {
			Class.forName("org.apache.log4j.Logger");
			setLoggerAdapter(new Log4jLoggerAdapter());
		} catch (ClassNotFoundException e) {
			setLoggerAdapter(new StdLoggerAdapter());
		}
	}

	public static void setLoggerAdapter(LoggerAdapter loggerAdapter) {
		if (loggerAdapter != null) {
			LoggerFactory.LOGGER_ADAPTER = loggerAdapter;
		}
	}

	public static Logger getLogger(Class<?> key) {
		Logger logger = LOGGERS.get(key.getName());
		if (logger == null) {
			LOGGERS.putIfAbsent(key.getName(), LOGGER_ADAPTER.getLogger(key.getName()));
			logger = LOGGERS.get(key.getName());
		}
		return logger;
	}

	public static Logger getLogger(String key) {
		Logger logger = LOGGERS.get(key);
		if (logger == null) {
			LOGGERS.putIfAbsent(key, LOGGER_ADAPTER.getLogger(key));
			logger = LOGGERS.get(key);
		}
		return logger;
	}

}